import { AppDispatch } from './../index';
import {
  ArticleCancelcollectionsApi,
  ArticleCancellikingsApi,
  ArticlecollectionsApi,
  ArticlelikingsApi,
  CancelfollowedApi,
  followingsApi,
  GetArticleByIdApi,
  GetArticleDetailByIdApi,
} from '@/api/articles';

/** 储存所有频道文章  复用action*/
export function SaveHomeListByIdAction(channel_id: number, timestamp?: number) {
  console.log('timestamp  ----->  ', timestamp);
  return async (dispatch: AppDispatch) => {
    let res = await GetArticleByIdApi({
      channel_id,
      timestamp: timestamp || Date.now(),
    });
    dispatch({
      type: 'articles/SaveHomeList',
      payload: { channel_id, ...res.data },
    });
  };
}

/** 覆盖指定频道内所有文章 action*/
export function ClearListByIdAction(channel_id: number) {
  return async (dispatch: AppDispatch) => {
    let res = await GetArticleByIdApi({
      channel_id,
      timestamp: Date.now(),
    });
    dispatch({
      type: 'articles/CoverListById',
      payload: { channel_id, ...res.data },
    });
  };
}

/** 根据文章Id获取文章详情 action*/
export function GetArticleDetailById(article_id: string) {
  return async (dispatch: AppDispatch) => {
    let res = await GetArticleDetailByIdApi(article_id);
    dispatch({ type: 'articles/SetArtcleDetail', payload: res.data });
  };
}

/** 清空文章详情 action*/
export function ClearDetailAction() {
  return { type: 'articles/ClearDetail' };
}

/** 点赞文章 action*/
export function ArticlelikingsAction(article_id: string, attitude: number) {
  return async (dispatch: AppDispatch) => {
    if (attitude === 1) {
      await ArticleCancellikingsApi(article_id);
    } else {
      await ArticlelikingsApi(article_id);
    }

    dispatch({
      type: 'articles/Setisattitude',
      payload: attitude === 1 ? -1 : 1,
    });
  };
}

/** 收藏 action*/
export function ArticlecollectionsAction(
  article_id: string,
  is_collected: boolean
) {
  return async (dispatch: AppDispatch) => {
    if (is_collected) {
      await ArticleCancelcollectionsApi(article_id);
    } else {
      await ArticlecollectionsApi(article_id);
    }
    dispatch({
      type: 'articles/Setis_collected',
      payload: !is_collected,
    });
  };
}

/** 关注 action*/
export function isFollowingsAction(aut_id: string, is_followed: boolean) {
  return async (dispatch: AppDispatch) => {
    if (is_followed) {
      await CancelfollowedApi(aut_id);
    } else {
      await followingsApi(aut_id);
    }
    dispatch({
      type: 'articles/Setis_followed',
      payload: !is_followed,
    });
  };
}
